package cn.dogger.easyboot.druid.aspect;

import cn.dogger.easyboot.druid.annotation.DataSource;
import cn.dogger.easyboot.druid.config.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class DataSourceAspect {


    /**
     * 切点: 所有配置 DataSource 注解的方法
     * annotation 在方法注解
     * within 在类上注解
     */
    @Pointcut("@annotation(cn.dogger.easyboot.druid.annotation.DataSource)|| @within(cn.dogger.easyboot.druid.annotation.DataSource)")
    public void dataSourcePointCut() {}

    //切面
    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        // 通过判断 DataSource 中的值来判断当前方法应用哪个数据源
        DataSource ds;
        //先尝试获取方法注解,如果为null,就拿类注解
        Method method = signature.getMethod();
        ds = method.getAnnotation(DataSource.class);
        if(ds == null){
        ds = AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
         //第二种方法,其它都拿不到在类注解
         //DataSource annotation = (DataSource) signature.getDeclaringType().getAnnotation(DataSource.class);
        }
        if(ds != null){
            DynamicDataSource.setDataSource(ds.value());
            log.info("切换{}数据源" , ds.value());
        }else{
            log.info("获取不到注解值! ");
        }
        try {
            //执行被切方法
            return point.proceed();
        } finally {
            //清除数据源配置,恢复默认
            DynamicDataSource.clearDataSource();
        }
    }
}
